<!--
 * @Author: Bennty
 * @Date: 2024-12-04 10:10:49
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-12-04 10:26:09
 * @Description: 请填写简介
-->
<template>
    <el-dialog :model-value="props.visible" title="查看产品配置" width="50%" @close="handleClose" destory-on-close>
        <el-row :gutter="20">
            <el-col :span="10">
                <el-form ref="formRef" :model="formData" label-width="auto">
                    <el-form-item label="产品配置名称" prop="combinationName" align="right">
                        <el-input disabled v-model="formData.combinationName"></el-input>
                    </el-form-item>
                    <el-form-item label="产品类型" prop="productType" align="right">
                        <el-select disabled v-model="formData.productType" multiple style="width: 100%" placeholder="请选择">
                            <el-option label="四色印刷" value="1"></el-option>
                            <el-option label="微定制" value="2"></el-option>
                        </el-select>
                    </el-form-item> 
                    <el-form-item label="生产产品" prop="procedureProduct">
                        <el-select disabled v-model="formData.procedureProduct" style="width: 100%" @change="handleProductChange" placeholder="请选择">
                            <el-option value="customization_indent_cap" label="生日帽"></el-option>
                            <el-option value="customization_indent_tableware" label="蛋糕餐具"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="产品款式" prop="productStyle">
                        <el-select disabled v-model="formData.productStyle" style="width: 100%" placeholder="请选择">
                            <el-option v-for="item in productStyleOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="产品图片" prop="imageUrl">
                        <el-upload
                            class="upload-demo"
                            ref="uploadRef"
                            drag
                            :action="uploadImgUrl"
                            :headers="headers"
                            v-model:file-list="fileList"
                            :on-success="handleSuccess" 
                            :before-upload="beforeUpload"
                            :on-exceed="handleExceed"
                            :limit="1"
                            disabled
                        >
                            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                            <div class="el-upload__text">
                            将文件拖入此处或<em>点击这里上传</em>
                            </div>
                            <template #tip>
                                <div class="el-upload__tip">
                                    jpg/png 文件不得超过 5MB
                                </div>
                            </template>
                        </el-upload>
                    </el-form-item>
                </el-form>
            </el-col>
            <el-col :span="12">
                <!-- <el-form-item label="添加产品类别">
                    <el-row :gutter="15">
                        <el-col :span="10">
                            <el-select v-model="selectedMajorType" filterable placeholder="产品大类" @change="handleMajorTypeChange">
                                <el-option v-for="item in types" :key="item.id" :label="item.majorName" :value="item.majorType"></el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="10">
                            <el-select v-model="selectedSubType" filterable placeholder="产品小类">
                                <el-option v-for="item in subclassTypes" :key="item.id" :label="item.subclassName" :value="item.subclassType"></el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="4">
                            <el-button type="success" :disabled="!shouldAdd" @click="onClickAddProduct" >添加</el-button>
                        </el-col>
                    </el-row>
                </el-form-item> -->
                <el-carousel height="200" style="width: 105%;height: 85%" :arrow="showArrow" :loop="false">
                    <el-carousel-item v-for="(item,index) in productCarouselItems" :key="index">
                        <el-row :gutter="10">
                            <el-col :span="8" v-for="(productSelect, productIndex) in item" :key="productIndex" style="margin-top:20px">
                                <el-select disabled v-model="productSelect.productId" :loading="loading" filterable @click="onClickSelect(productSelect)" placeholder="请选择">
                                    <el-option v-for="auxiliaries in productSelect.auxiliaryList" :key="auxiliaries.id" :value="auxiliaries.id" :label="auxiliaries.specsDetail"></el-option>
                                </el-select>
                                <!-- <el-button type="danger" icon="Close" link @click="handleDeleteProduct(index, productIndex)" ></el-button> -->
                            </el-col>
                        </el-row>
                    </el-carousel-item>
                </el-carousel>
            </el-col>
        </el-row>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { type FormInstance,UploadInstance, UploadProps, UploadUserFile, UploadRawFile  } from 'element-plus';
import {  Form } from '@/api/sj/productManagement/productConfigure/types';
import { genFileId } from 'element-plus'
import { globalHeaders } from "@/utils/request";
import { getSingleByTotalApi } from '@/api/sj/warehouse/typeManagement';
import { getAuxiliaryByTypeApi } from '@/api/sj/warehouse/auxiliary';

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/resource/oss/upload");
const headers = ref(globalHeaders);

const props = defineProps<{
    visible: boolean,
    formModel: any,
    caps: any[],
    tableWare: any[],
    types: any[]
}>();
const emits = defineEmits(['close','submit']);
const formRef = ref<FormInstance>();
const uploadRef = ref<UploadInstance>();
const formData = ref<Form>({});
const productStyleOptions = ref<any[]>([]);
const supportFileTypes = ['image/jpeg', 'image/png'];

const products = ref<any[]>([]);
const subclassTypes = ref<any[]>([]);
const selectedMajorType = ref<any>();
const selectedSubType = ref<any>();
const shouldAdd = ref(false);
const auxiliaryList = ref<any[]>([]);
const productCarouselItems = ref<any[]>([]);
const showArrow = ref('never');
const loading = ref(false);
const fileList = ref<UploadUserFile[]>([]);

watch(()=>props.formModel, async (newData)=>{
    if(props.visible){
        formData.value = newData;
        formData.value.productType = newData.productType.split(',');
        fileList.value = [{name: 'image1',url: newData.imageUrl}];
        try{
                const dataList = await Promise.all(
                    newData.dataList.map(async (item: any)=>{
                        console.log(item);
                        const { data } = await getAuxiliaryByTypeApi(item.productCategoriesType, item.productSubcategoryType);
                        return {
                            ...item,
                            auxiliaryList: data
                        };
                })
            );
            // console.log(dataList);
            products.value = [...dataList];
        }catch(error){
            console.error('Error fetching auxiliary data:', error);
        };
    };
    // products.value = [...dataList];
});

watch(()=>formData.value.procedureProduct,(newData: any)=>{
    if(newData == 'customization_indent_cap'){
        productStyleOptions.value = props.caps;
    }else if(newData == 'customization_indent_tableware'){
        productStyleOptions.value = props.tableWare;
    }else{
        productStyleOptions.value = [];
    };
});

const handleProductChange = (value: string) => {
    formData.value.productStyle = undefined;
};

const handleSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    console.log(URL.createObjectURL(uploadFile.raw!),response);
    //@ts-ignore
    // formData.value.imageUrl = URL.createObjectURL(uploadFile.raw!);
    formData.value.imageUrl = response.data.url;
};

const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (!supportFileTypes.includes(rawFile.type)) {
        ElMessage.error('图片格式与要求不符')
        return false
    } else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('图片不可超过 5MB!')
        return false
    }
    return true;
};

const handleExceed: UploadProps['onExceed'] = (files) => {
    uploadRef.value!.clearFiles();
    const file = files[0] as UploadRawFile;
    file.uid = genFileId();
    uploadRef.value!.handleStart(file);
    uploadRef.value!.submit();
};

/** 根据材料大类，获取材料小类 */
watch(()=>selectedMajorType.value,async (newData)=>{
    if(selectedMajorType.value){
        const { code, data } = await getSingleByTotalApi(newData);
        if(code == 200){
            subclassTypes.value = data;
        };
    };
});

/** 选择大类，清除小类与产品选项 */
const handleMajorTypeChange = () => {
    selectedSubType.value = undefined;
};

/** 根据材料大类与材料小类，获取辅材列表 */
watch(()=>[selectedMajorType.value, selectedSubType.value],async ([newlyMajorType, newlySubType])=>{
    // console.log(newlyMajorType, newlySubType);
    if(newlyMajorType && newlySubType){
        shouldAdd.value = true;
        // const { code, data } = await getAuxiliaryByTypeApi(newlyMajorType, newlySubType);
        // if(code == 200){
        //     auxiliaryList.value = data;
        // };
    }else{
        shouldAdd.value = false;
    };
});

/** 添加材料 */
const onClickAddProduct = () => {
    products.value.push({
        productId: undefined,
        productCategoriesType: selectedMajorType.value,
        productSubcategoryType: selectedSubType.value,
        combinationId: props.formModel.id,
        auxiliaryList: []
    });
};

const onClickSelect = async (item: any) => {
    if(item.auxiliaryList){
        loading.value = true;
        const { code, data } = await getAuxiliaryByTypeApi(item.productCategoriesType, item.productSubcategoryType);
        if(code == 200){
            item.auxiliaryList = data;
        };
        loading.value = false;
    };
};

const handleDeleteProduct = (carouselIndex: number, itemIndex: number) => {
    productCarouselItems.value[carouselIndex].splice(itemIndex, 1);
    // console.log(productCarouselItems.value);
    const productsBak:any[] = [];
    for(let i = 0; i<productCarouselItems.value.length;i++){
        productCarouselItems.value[i].forEach((item: any)=>{
            productsBak.push(item);
        });
    };
    products.value = [...productsBak];
};

/** 给轮播图分组 */
watch(()=>products.value, (newValue)=>{
    const groupNumber = Math.ceil((newValue.length + 1) / 15);
    if(groupNumber > 1){
        showArrow.value = 'hover';
    }else{
        showArrow.value = 'never';
    };
    const productBak = [...newValue];
    const productByGroup = [];
    for(let i=0;i<groupNumber;i++){
        const group = productBak.splice(0,15);
        // console.log(group);
        productByGroup.push(group);
        // console.log(productByGroup.length);
    };
    productCarouselItems.value = [...productByGroup];
    // console.log(productCarouselItems.value);
},{deep: true});


const handleClose = () => {
    formRef.value?.resetFields();
    uploadRef.value?.clearFiles();
    products.value = [];
    emits('close');
};
</script>

<style scoped>

</style>